package com.xshiwu.utils;

import com.xshiwu.pojo.Content;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**
 * 爬取京东工具类
 */
@Component
public class HtmlParseUtil {
    /**
     *
     * @param keywords 搜索关键字
     * @return list
     */
    public List<Content> parseJd(String keywords) throws IOException {
        // https://ai.taobao.com/search/index.htm?key=java
        String url = "https://search.jd.com/Search?keyword="+ keywords+"&enc=utf-8";
        Document document = Jsoup.parse(new URL(url), 30000);
        // 获取id为J_goodsList的div
        Element element = document.getElementById("J_goodsList");
        // 获取所有的li元素
        Elements elementLi = element.getElementsByTag("li");
        List<Content> list = new ArrayList<>();
        for (Element el : elementLi) {
            if (el.attr("class").equalsIgnoreCase("gl-item")){
                // 获取li下面为img的标签里面的src属性
            String img = el.getElementsByTag("img").eq(0).attr("data-lazy-img");
            // 价格
            String price = el.getElementsByClass("p-price").eq(0).text();
            // 标题
            String title = el.getElementsByClass("p-name").eq(0).text();
            Content content = new Content();
            content.setImg(img);
            content.setPrice(price);
            content.setTitle(title);
            list.add(content);
            }
        }
        return list;
    }
}
